package com.lxmes.device.service.impl;

import com.lxmes.common.annotation.DataScope;
import com.lxmes.common.config.RuoYiConfig;
import com.lxmes.common.core.domain.entity.SysUser;
import com.lxmes.common.exception.ServiceException;
import com.lxmes.common.utils.*;
import com.lxmes.device.domain.DeviceFailureRepair;
import com.lxmes.device.domain.DeviceFailureReport;
import com.lxmes.device.mapper.DeviceFailureRepairMapper;
import com.lxmes.device.mapper.DeviceFailureReportMapper;
import com.lxmes.device.service.IDeviceFailureReportService;
import com.lxmes.device.utils.WaterMarkUtils;
import com.lxmes.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 设备故障报修单Service业务层处理
 * 
 * @author 张志煜
 * @date 2022-04-18
 */
@Service
public class DeviceFailureReportServiceImpl implements IDeviceFailureReportService 
{
    @Autowired
    private DeviceFailureReportMapper deviceFailureReportMapper;
    @Autowired
    private  DeviceFailureRepairServiceImpl repairService;
    @Autowired
    private DeviceFailureRepairMapper repairMapper;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询设备故障报修单
     * 
     * @param id 设备故障报修单主键
     * @return 设备故障报修单
     */
    @Override
    public DeviceFailureReport selectDeviceFailureReportById(Long id)
    {
        return deviceFailureReportMapper.selectDeviceFailureReportById(id);
    }

    @Override
    public DeviceFailureReport selectDeviceFailureReportByReportId(String reportId) {
        return deviceFailureReportMapper.selectDeviceFailureReportByReportId(reportId);
    }

    /**
     * 查询设备故障报修单列表
     * 
     * @param deviceFailureReport 设备故障报修单
     * @return 设备故障报修单
     */
    @Override
    @DataScope(deptAlias = "dfr", userAlias = "dfr")
    public List<DeviceFailureReport> selectDeviceFailureReportList(DeviceFailureReport deviceFailureReport)
    {
        return deviceFailureReportMapper.selectDeviceFailureReportList(deviceFailureReport);
    }
    /**
     * 查询API全部设备故障报修单列表
     *
     * @param deviceFailureReport 设备故障报修单-全部
     * @return 设备故障报修单集合
     */
    @Override
    @DataScope(deptAlias = "dfr", userAlias = "dfr")
    public List<DeviceFailureReport> selectApiDeviceFailureReportList(DeviceFailureReport deviceFailureReport) {
        return deviceFailureReportMapper.selectApiDeviceFailureReportList(deviceFailureReport);
    }
    /**
     * 查询API全部设备故障维修单列表
     *
     * @param deviceFailureReport 设备故障维修单-全部
     * @return 设备故障报修单集合
     */
    @Override
    public List<DeviceFailureReport> selectApi1DeviceFailureReportList(DeviceFailureReport deviceFailureReport) {
        return selectApi1DeviceFailureReportList(deviceFailureReport);
    }

    /**
     * 新增设备故障报修单
     * 
     * @param deviceFailureReport 设备故障报修单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDeviceFailureReport(DeviceFailureReport deviceFailureReport) throws Exception {
        deviceFailureReport.setFaultProgress("0");
        String number= NewNumber.createNewNumber(deviceFailureReportMapper.getNewCode(DateUtils.getDate()));
        deviceFailureReport.setReportId("GZBX-"+number);
        //deviceFailureReport.setReportId("GZBX-"+DateUtils.dateTimeNow());
        SysUser user = sysUserService.selectUserById(SecurityUtils.getUserId());
        deviceFailureReport.setReportName(user.getNickName());
        deviceFailureReport.setReportPhone(user.getPhonenumber());
        deviceFailureReport.setOccurrenceTime(DateUtils.getTime());
        deviceFailureReport.setUserId(SecurityUtils.getUserId().toString());
        deviceFailureReport.setCreateTime(DateUtils.getNowDate());
        if(StringUtils.isNotNull(deviceFailureReport.getFaultImg())){
            String path[]= deviceFailureReport.getFaultImg().split(",");
            for (int i = 0; i <path.length ; i++) {
                WaterMarkUtils.resizeImage(path[i],360,600);
                WaterMarkUtils.creat(path[i],"报修人："+deviceFailureReport.getReportName(),"发生时间："+deviceFailureReport.getOccurrenceTime());
                WaterMarkUtils.commPressPicCycle(path[i],0.8);
            }
        }
        if(deviceFailureReport.getDeptId()==null|| deviceFailureReport.getDeptId().longValue() == 0){
            deviceFailureReport.setDeptId(SecurityUtils.getDeptId());
        }
        this.validEntityBeforeSaveOrUpdate(deviceFailureReport);
         deviceFailureReportMapper.insertDeviceFailureReport(deviceFailureReport);
         if(RuoYiConfig.isIsSendSms()){
             user=sysUserService.selectUserById(102L);
             if(StringUtils.isNotNull(user)){
                 if(StringUtils.isNotBlank(user.getPhonenumber())){
                     Sample.sendSms(user.getPhonenumber(),deviceFailureReport.getReportId(),"SMS_241057261");
                 }
             }
         }
         return  1;
    }

    /**
     * 修改设备故障报修单
     * 
     * @param deviceFailureReport 设备故障报修单
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDeviceFailureReport(DeviceFailureReport deviceFailureReport)
    {
        this.validEntityBeforeSaveOrUpdate(deviceFailureReport);
        if(deviceFailureReport.getDeptId()==null|| deviceFailureReport.getDeptId().longValue() == 0){
            deviceFailureReport.setDeptId(SecurityUtils.getDeptId());
        }
        deviceFailureReport.setUpdateTime(DateUtils.getNowDate());
        deviceFailureReport.setUserId(SecurityUtils.getUserId().toString());
        return deviceFailureReportMapper.updateDeviceFailureReport(deviceFailureReport);
    }
    public void  validEntityBeforeSaveOrUpdate(DeviceFailureReport deviceFailureReport){
        int v=deviceFailureReportMapper.validEntityBeforeSaveOrUpdate(deviceFailureReport);
        if(v>0){
            throw new ServiceException("故障报修单ID"+deviceFailureReport.getReportId()+"已存在");
        }

    }
    /**
     * 批量删除设备故障报修单
     * 
     * @param ids 需要删除的设备故障报修单主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDeviceFailureReportByIds(Long[] ids)
    {
        for (int i = 0; i <ids.length ; i++) {
            DeviceFailureReport report = deviceFailureReportMapper.selectDeviceFailureReportById(ids[i]);
            if(StringUtils.isNotBlank(report.getReportId())){
                repairMapper.deleteDeviceFailureRepairByReportId(report.getReportId());
            }
        }
        return deviceFailureReportMapper.deleteDeviceFailureReportByIds(ids);
    }

    @Override
    @Transactional
    public int insertDeviceFailureReportJobSub(String reportId, Long majorId, Long[] fzMajorId) throws Exception {
            String phone="";
        DeviceFailureReport report =deviceFailureReportMapper.selectDeviceFailureReportByReportId(reportId);
         /*   if(StringUtils.isNotBlank(report.getMajor())){
                throw new ServiceException(report.getReportId()+"此报修单已派工");
            }*/
            SysUser major = sysUserService.selectUserById(majorId);
            if(StringUtils.isNull(major)){
                throw new ServiceException("未找到主维修人"+majorId);
            }
            phone+=major.getPhonenumber()+",";
            report.setMajor(major.getNickName());
            report.setMajorId(majorId);
            String fzMajorIds=" ";
            String fzMaJorNames=" ";
            for (int j = 0; j <fzMajorId.length ; j++) {
                if(fzMajorId[j].longValue() == majorId.longValue()){
                    continue;
                }
                SysUser fzMajor = sysUserService.selectUserById(fzMajorId[j]);
                if(StringUtils.isNull(fzMajor)){
                    continue;
                }else {
                    fzMajorIds+=fzMajor.getUserId()+",";
                    fzMaJorNames+=fzMajor.getNickName()+",";
                    phone+=major.getPhonenumber()+",";
                }
            }
            if(StringUtils.isNotBlank(fzMaJorNames)&&StringUtils.isNotBlank(fzMajorIds)){
                report.setFzMaJors(fzMaJorNames.substring(0,fzMaJorNames.length()-1));
                report.setFzMajorIds(fzMajorIds.substring(0,fzMajorIds.length()-1));
            }
            report.setFaultProgress("1");
            DeviceFailureRepair repair = repairService.selectDeviceFailureRepairByReportId(reportId);
            if(StringUtils.isNull(repair)){
                deviceFailureReportMapper.updateDeviceFailureReportJobSub(report);repair=new DeviceFailureRepair();
            repair.setReportId(report.getReportId());
            String number= NewNumber.createNewNumber(repairMapper.getNewCode(DateUtils.getDate()));
            repair.setRepairId("GZWX-"+number);
                //repair.setRepairId("GZWX-"+DateUtils.dateTimeNow());
            repair.setUserId(report.getMajorId());
            repair.setDeptId(report.getDeptId());
            repair.setMajor(report.getMajor());
            repair.setMajorId(report.getMajorId());
            repair.setFzMajorIds(report.getFzMajorIds());
            repair.setFzMajors(report.getFzMaJors());
            repair.setRepairDept(report.getWxDept());
            repair.setDeviceName(report.getDeviceName());
            repair.setDeviceCode(report.getDeviceCode());
            repair.setFaultProgress(report.getFaultProgress());
/*
            repair.setStartTime(DateUtils.getTime());
*/
           repairService.insertDeviceFailureRepair(repair);
          //短信发送维修工
            if(RuoYiConfig.isIsSendSms()) {
                if (StringUtils.isNotBlank(phone)) {
                    phone = phone.substring(0, phone.length() - 1);
                    Sample.sendSms(phone, repair.getRepairId(), "SMS_241077493");

                }
                //通知回传报修工
                if (StringUtils.isNotBlank(report.getReportPhone())) {
                    Sample.sendSms(report.getReportPhone(), repair.getRepairId(), "SMS_241057639");
                }
            }
            }else {
                throw new ServiceException(report.getReportId()+"不能重复派单");
            }
        return 1;
    }

    @Override
    public int cancelReport(Long id, String remark) {
        DeviceFailureReport report =deviceFailureReportMapper.selectDeviceFailureReportById(id);
        if(StringUtils.isNull(report)){
            throw new ServiceException("未找报修单撤销失败！");
        }
        if(StringUtils.equals(report.getFaultProgress(),"4")){
            throw new ServiceException("此报修单已完成维修不能撤销");
        }
        report.setFaultProgress("0");
        report.setRemark(remark);
        return  deviceFailureReportMapper.updateDeviceFailureReport(report);
    }

    /**
     * 删除设备故障报修单信息
     * 
     * @param id 设备故障报修单主键
     * @return 结果
     */
    @Override
    public int deleteDeviceFailureReportById(Long id)
    {
        return deviceFailureReportMapper.deleteDeviceFailureReportById(id);
    }

    @Override
    public int apiCancelFailureReport(String  reportId) {
        DeviceFailureReport report = deviceFailureReportMapper.selectDeviceFailureReportByReportId(reportId);
       if(!report.getFaultProgress().equals("0")){
           throw new ServiceException("此报修单已接单不能取消");
       }
        return deviceFailureReportMapper.deleteDeviceFailureReportById(report.getId());
    }
}
